﻿#region License

// // -------------------------------------------------------------------------------------
// // This information refers to LogDurationAspect.cs
// // 
// // Copyright 2012 ELEN7046 Group 2
// // 
// // Last Modified on: 2012-06-10
// // 
// // Contributors:
// // 
// // Amith Sewnarain
// // Elmar Vosloo
// // Jason Thorne
// // Satish Jewan
// // 
// // Wits University 
// // School of Electrical & Information Engineering
// // Software Engineering Tools and Techniques
// // 
// // -------------------------------------------------------------------------------------
// // 
// // This file (LogDurationAspect.cs) is part of the DishDash Event Visualization System.
// // 
// // DishDash is free software: you can redistribute it and/or modify
// // it under the terms of the GNU General Public License as published by
// // the Free Software Foundation, either version 3 of the License, or
// // (at your option) any later version.
// // 
// // DishDash is distributed in the hope that it will be useful,
// // but WITHOUT ANY WARRANTY; without even the implied warranty of
// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// // GNU General Public License for more details.
// // 
// // You should have received a copy of the GNU General Public License
// // along with DishDash.  
// // If not, see <http://www.gnu.org/licenses/>.
// // -------------------------------------------------------------------------------------

#endregion

#region Using Directives

using System;
using System.Linq;
using InstrumentationLibrary;
using InstrumentationWrapper;
using Mono.Cecil;
using Mono.Cecil.Cil;

#endregion

namespace InstrumentAspect
{
    internal class LogDurationAspect : IInstrumentationAspect
    {
        private InstrumentationAttribute _identifyingAttributeInstance = new LogDurationAttribute();

        #region IInstrumentationAspect Members

        /// <summary>
        ///   Gets or sets the identifying attribute.
        /// </summary>
        /// <value> The identifying attribute. </value>
        public InstrumentationAttribute IdentifyingAttribute
        {
            get { return _identifyingAttributeInstance; }
            set { _identifyingAttributeInstance = value; }
        }

        /// <summary>
        ///   Instruments the specified method.
        /// </summary>
        /// <param name="method"> The method. </param>
        public void Instrument(MethodDefinition method)
        {
            var aspectMethod = typeof (InstrumentationWrapperService).GetMethod("LogDuration",
                                                                                       new Type[]
                                                                                           {
                                                                                               typeof (string),
                                                                                               typeof (DateTime)
                                                                                           });

            MethodReference aspectReference = null;
            aspectReference = method.Module.Import(aspectMethod);

            //Get the existing instructions
            var existingInstructions = method.Body.Instructions.ToArray();
            method.Body.Instructions.Clear();

            var dateTimeType = method.Module.Import(typeof (DateTime));
            //Create the date time variable
            var dateNow = new VariableDefinition(method.Module.Import(typeof (DateTime)));
            var dateTimeDefinition = dateTimeType.Resolve();
            //Get the DateTime.Now function
            var nowMethod = method.Module.Import(dateTimeDefinition.Methods.First(x => x.Name == "get_Now"));
            //Add the variable to the method
            method.Body.Variables.Add(dateNow);

            //Insert the variable. Use loc_s so that we can associate to the date variable we created
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, nowMethod));
            method.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc_S, dateNow));

            //Put back the existing instructions
            foreach (var existingInstruction in existingInstructions)
            {
                //Check for Return opcodes and add call to log duration before the return
                //Note that OpCodes.Leave_S will result in code insert before exiting the try and before exiting the catch. 
                //Should we rather check for Leave_S or Ret. Ret will only add the method when the method completes.
                if (existingInstruction.OpCode == OpCodes.Ret) // || existingInstruction.OpCode == OpCodes.Leave_S)
                {
                    //Add the parameter for the string first
                    method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr,
                                                                    (method.DeclaringType.FullName + "." + method.Name +
                                                                     ".duration").ToLower()));
                    //Now the local variable for datetime
                    method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc_S, dateNow));
                    //Call the method
                    method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, aspectReference));
                }
                method.Body.Instructions.Add(existingInstruction);
            }
        }

        #endregion
    }
}